<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 会员接口
 */
namespace app\allwin\controller\api\v4;
use app\allwin\controller\api\Base;
use app\allwin\model\VipCard;
use app\allwin\model\AllwinUser;
use app\allwin\model\Vip as AllwinVip;
use app\allwin\model\AllwinConfig;
use app\allwin\model\MchId;
use app\allwin\model\CouponUser;
use app\allwin\model\Bank;
use app\allwin\model\Levels;
use app\allwin\model\Coupon;
use app\common\facade\WechatPay;
use app\allwin\widget\Vip as VipIncome;

class Vip extends Base{

    /**
     * 初始化当前应用管理员是不是联盟城市账户
     * @return void
     */
    public function initialize() {
        parent::initialize();
        $this->isUserAuth();
    }
  
    /**
     * 判断是否VIP和是否允许升级
     */
    public function isVip(){
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $data = ['isvip' => 0,'is_up' => 1,'icard' => [],'card' => []];
        $vipuser = AllwinVip::with(['vipcard'=> function($query) {
            $query->field('id,coupon_num,is_up,price,name,tips,rule');
        }])->where(['user_id' => $this->user->id,'state' => 1,'is_lock' => 0])->field('is_up,vipcard_id')->find();
        $condition   = [];
        $condition[] = ['member_miniapp_id','=',$this->miniapp_id];
        if($vipuser){
            $bank  = Bank::where(['user_id' => $this->user->id])->field('income_money')->find(); //收益
            $store = AllwinUser::where(['uid' => $this->user->id])->find();  //所属店铺
            $data['isvip'] = 1;
            $data['is_up'] = $vipuser->vipcard->is_up;
            $data['icard'] = $vipuser->vipcard;
            $data['icard']['title']    = empty($store->store) ? $this->miniapp->appname.'会员' : $store->store->name.'会员';
            $data['icard']['store_id'] = empty($store->store)?0:$store->store_id;
            $data['icard']['income_money'] = empty($bank) ? 0 : round($bank->income_money/100);
            $data['icard']['rule'] = str_replace('<img', '<img class="img" style="max-width:100%;height:auto"',dehtml($vipuser->vipcard->rule));
            $condition[] = ['id','<>',$vipuser->vipcard_id];
        }
        $data['card'] = VipCard::where($condition)->field('id,coupon_num,is_up,price,name,tips,rule')->order('sort desc,id desc')->find();
        if(empty($data['card'])){
            $data['card'] = [];
        }else{
            $data['card']['rule'] = str_replace('<img', '<img class="img" style="max-width:100%;height:auto"',dehtml($data['card']['rule']));
            $data['card']['price'] = round($data['card']['price']);
        }
        if($data['isvip'] == 1){
            $data['num'] = Levels::where(['parent_id' => $this->user->id,'level' => [1,2]])->count();
        }else{
            $data['num'] = AllwinVip::where(['state' => 1,'is_lock' => 0,'member_miniapp_id'=>$this->miniapp_id])->count();
        }
        if(empty($data['icard']) && empty($data['card'])){
            return enjson(204,'没有开通会员服务');
        }
        return enjson(200,'成功',$data);
    }

    /**
     * 开通会员中心
     * @return boolean
     */
    public function payment(){
        if (request()->isPost()) {
            $param = [
                'vipcard'    => $this->request->param('vipcard/d'),
                'ucode'      => $this->request->param('ucode/s',''),
                'signkey'    => $this->request->param('signkey'),
                'sign'       => $this->request->param('sign'),
            ];
            $rel = $this->apiSign($param);
            if($rel['code'] != 200){
                return enjson(403,'签名验证失败');
            }
            $card_id = $param['vipcard'];
            $vipcard = VipCard::where(['id' => $card_id])->field('id,price,is_up,name,coupon_ids')->find();
            if(empty($vipcard)){
                return enjson(403,'未找到要开通的会员类型');
            }
            $is_vip = AllwinVip::where(['id' => $vipcard->id,'state' => 1])->count();
            if($is_vip){
                return enjson(403,'你已经是会员');
            }
            //判断并读取邀请用户的所属店铺ID
            $store_id = 0;
            $ucode = de_code(strtoupper($param['ucode']));
            if($ucode){
                $vipuser = AllwinUser::where(['uid' => $ucode])->find();
                if($vipuser){
                    if($this->miniapp_id != $vipuser->user->member_miniapp_id){
                        return enjson(403,'邀请用户填写不正确');
                    }
                    $store_id = $vipuser['store_id'];
                }
            }
            //数据
            $coupon_ids = explode(',',$vipcard->coupon_ids);
            $order_no                     = 'VIP'.order_no();
            $vipdata                      = [];
            $vipdata['state']             = $vipcard->price <= 0 ? 1 : 0;
            $vipdata['is_lock']           = 0;
            $vipdata['coupon_ids']        = empty($coupon_ids)? '[]' : json_encode($coupon_ids);
            $vipdata['order_no']          = $order_no;
            $vipdata['amount']            = $vipcard->price;
            $vipdata['is_up']             = $vipcard->is_up; 
            $vipdata['vipcard_id']        = $vipcard->id;
            $vipdata['store_id']          = $store_id;     //邀请参数的店铺ID
            $vipdata['from_ucode']        = $param['ucode'];//邀请人的邀请码
            $vipdata['user_id']           = $this->user->id;
            $vipdata['member_miniapp_id'] = $this->miniapp_id;
            $vipdata['update_time']       = time();
            //判断帐号
            $rel = AllwinVip::where(['member_miniapp_id'=>$this->miniapp_id,'user_id' => $this->user->id,'state' => 0])->find();
            if($rel){
                AllwinVip::where(['id' => $rel->id])->update($vipdata);
                $vip_id = $rel->id;
            }else{
                $allwinVip = AllwinVip::create($vipdata);
                $vip_id = $allwinVip->id;
            }
            //如果免费
            if($vipcard->price <= 0){
                //增加邀请关系
                if(!empty($ucode)){
                    VipIncome::addLevel($this->user->id,$ucode,$store_id);
                }
                //更新VIP状态
                AllwinVip::where([['user_id','=',$this->user->id],['state','=','1'],['id','<>',$vip_id]])->update(['is_lock' => 1]);
                //赠送优惠券
                CouponUser::addUserCoupon($vipdata['coupon_ids'],$this->user->id);
                //统计优惠综合
                $coupon_aumont = Coupon::where(['id' => $coupon_ids])->sum('size');
                
                return enjson(200,'成功加入会员',['isvip' => 1,'coupon_aumont'=> $coupon_aumont]); 
            }else{
                $payparm = [
                    'openid'       => $this->user->miniapp_uid,
                    'miniapp_id'   => $this->miniapp_id,
                    'order_no'     => $order_no,
                    'total_fee'    => $vipcard->price*100,
                    'name'         => '开通'.$vipcard->name,
                    'notify_url'   => api(4,'allwin/vipnotify/index',$this->miniapp_id),
                ];
                //读取配置
                $setting = AllwinConfig::getConfig($this->miniapp_id);
                if($setting->is_psp == 1){
                    $default_mchid = MchId::getMch(0,$this->miniapp_id);  //默认收款账户
                    if (empty($default_mchid)) {
                        return enjson(403,'未找到收款账号');
                    }
                    $payparm['mchid'] = $default_mchid->mchid;  
                }
                $ispay = WechatPay::orderPay($payparm);
                if($ispay['code'] == 0){
                    return json(['code'=>403,'msg'=>$ispay['msg']]);
                }
                return enjson(200,'开始付款',['isvip' => 0,'pay' => $ispay['data']]); 
            }
        }
    }

    /**
     * 读取会员专属优惠券
    */
    public function coupon(){
        $param['vipid']  = $this->request->param('vipid/d');
        $param['page']   = $this->request->param('page/d',0);
        $param['sign']   = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson(403,'签名失败');
        }
        $vipuser = VipCard::where(['id' => $param['vipid']])->field('coupon_ids')->find();
        if (empty($vipuser)) {
            return enjson(204,'没有优惠券');
        }
        $condition[] = ['id','in',$vipuser->coupon_ids];
        $condition[] = ['is_lock','=',0];
        $condition[] = ['is_end','=',0];
        $condition[] = ['num','>',0];
        $condition[] = ['endtime','>',time()];
        $coupon = Coupon::where($condition)->field('id,name,size,tips,discount,price,types')->order('is_top desc,sort desc,size desc')->paginate(6);
        if ($coupon->isEmpty()) {
            return enjson(204,'没有优惠券');
        }
        $data = [];
        foreach ($coupon as $key => $value) {
            $data[$key]['id']        = $value['id'];
            $data[$key]['name']      = $value['name'];
            $data[$key]['amount']    = round($value['size']);
            $data[$key]['tips']      = $value['tips'];
            $data[$key]['types']     = $value['types'];
            $data[$key]['price']     = $value['types'] ? $value['discount'].'折':$value['price'];
        }
        return enjson(200,'成功',$data);
    }
}